<template>
  <div class="all">
    <div class="item" v-for="(item, index) in _threshold" :key="keys[index]">
      <span class="label">{{ label }}{{ index + 1 }}</span>
      <view class="input-box">
        <span class="input"
          >{{ thresholdLeftLabel }}<input v-model="_threshold[index]" @blur="() => maintenanceIndexData(index)" />{{ thresholdRightLabel }}
          {{ valueLeftLabel }}<input v-model="_value[index]" @blur="() => maintenanceIndexData(index)" />{{ valueRightLabel }}</span
        >
        <span class="operation"
          ><button class="but" @click.prevent="add(index)">+</button> <button class="but" @click.prevent="remove(index)">-</button>
        </span>
      </view>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
const _threshold = ref<string[]>([''])
const _value = ref<string[]>([''])
const keys = ref<string[]>([nowTime()])
const props = defineProps({
  threshold: {
    default: [] as string[] | number[] | string
  },
  value: {
    default: [] as string[] | number[] | string
  },
  stringModeSeparator: {
    type: String,
    default: ','
  },
  stringMode: {
    type: Boolean,
    default: null
  },
  thresholdLeftLabel: {
    type: String,
    default: '满'
  },
  thresholdRightLabel: {
    type: String,
    default: '元'
  },
  valueLeftLabel: {
    type: String,
    default: '减'
  },
  valueRightLabel: {
    type: String,
    default: '元'
  },
  limit: {
    type: String,
    default: 'gt' // lt gt eq null
  },
  label: {
    type: String,
    default: '满减优惠'
  }
})

function limitCheck(threshold: number, value: number): boolean {
  switch (props.limit) {
    case 'lt':
      return threshold < value
    case 'gt':
      return threshold > value
    case 'eq':
      return threshold === value
    case null:
      return true
    default:
      return false
  }
}
const isStringMode = ref(typeof props.threshold === 'string')
const emit = defineEmits<{
  (e: 'update:threshold', value: string | string[]): void
  (e: 'update:value', value: string | string[]): void
}>()
// 看两个数组是否完全相等
function arraysAreEqual<T>(a: T[], b: T[]): boolean {
  if (a.length !== b.length) {
    return false
  }
  return a.every((val, index) => val === b[index])
}
watch(
  () => [props.threshold, props.value],
  ([threshold, value]) => {
    // 判断外部的与内部的是否完全相等
    const thresholdArr = Array.isArray(threshold)
      ? threshold.map((item) => item + '')
      : threshold == null || threshold == ''
      ? []
      : threshold.split(props.stringModeSeparator)

    const valueArr = Array.isArray(value)
      ? value.map((item) => item + '')
      : value == null || value == ''
      ? []
      : value.split(props.stringModeSeparator)
    if (arraysAreEqual(thresholdArr, _threshold.value) && arraysAreEqual(valueArr, _value.value)) return
    // 外部->内部
    if (props.stringMode != null) isStringMode.value = props.stringMode
    if (props.threshold.length > 0) {
      // 回显threshold
      _threshold.value = isStringMode.value
        ? props.threshold == null || props.threshold === ''
          ? []
          : (props.threshold as string).split(props.stringModeSeparator)
        : (props.threshold as number[] | string[]).map((item) => item + '')
      // 回显value
      _value.value = isStringMode.value
        ? props.value == null || props.value === ''
          ? []
          : (props.value as string).split(props.stringModeSeparator)
        : (props.value as number[] | string[]).map((item) => item + '')
      // 设置初始keys
      keys.value = _threshold.value.map((item) => nowTime())
    }
  },
  { deep: true, immediate: true }
)

function nowTime() {
  return Date.now() + ''
}

function maintenanceIndexData(index: number) {
  let thresholdOfIndex = isNaN(parseFloat(_threshold.value[index])) ? 0 : parseFloat(_threshold.value[index])
  let valueOfIndex = isNaN(parseFloat(_value.value[index])) ? 0 : parseFloat(_value.value[index])
  if (!limitCheck(thresholdOfIndex, valueOfIndex)) {
    valueOfIndex = thresholdOfIndex
  }
  _threshold.value[index] = thresholdOfIndex == 0 ? '' : thresholdOfIndex + ''
  _value.value[index] = valueOfIndex == 0 ? '' : valueOfIndex + ''

  // 从小到大同步排序
  if (_threshold.value.filter((item) => isNaN(parseFloat(item))).length == 0 && _value.value.filter((item) => isNaN(parseFloat(item))).length == 0) {
    for (let i = 0; i < _threshold.value.length; i++) {
      for (let j = 0; j < _threshold.value.length - 1; j++) {
        if (Number(_threshold.value[j]) > Number(_threshold.value[j + 1])) {
          let temp = _threshold.value[j]
          _threshold.value[j] = _threshold.value[j + 1]
          _threshold.value[j + 1] = temp

          let temp2 = _value.value[j]
          _value.value[j] = _value.value[j + 1]
          _value.value[j + 1] = temp2
        }
      }
    }
    emit('update:threshold', _threshold.value.join(props.stringModeSeparator))
    emit('update:value', _value.value.join(props.stringModeSeparator))
  }
}

function add(index: number) {
  // keys向后移一位
  for (let i = keys.value.length - 1; i >= index + 1; i--) {
    keys.value[i + 1] = keys.value[i]
  }
  keys.value[index + 1] = nowTime()
  // 在Index后面加一个
  // 将现在threshold的index及后面的向后移一位
  for (let i = _threshold.value.length - 1; i >= index + 1; i--) {
    _threshold.value[i + 1] = _threshold.value[i]
  }
  _threshold.value[index + 1] = ''
  // 将现在value的index及后面的向后移一位
  for (let i = _value.value.length - 1; i >= index + 1; i--) {
    _value.value[i + 1] = _value.value[i]
  }
  _value.value[index + 1] = ''
}
function remove(index: number) {
  if (keys.value.length == 1) return
  keys.value.splice(index, 1)
  _threshold.value.splice(index, 1)
  _value.value.splice(index, 1)
}
</script>

<style scoped lang="scss">
.all {
  .item {
    margin-bottom: 10px;

    .input-box {
      .input {
        margin-left: 20px;

        input {
          margin: 0 10px;
          padding: 3px 10px;
          width: 60px;
          border: 1px solid rgb(125 125 125);
          border-radius: 3px;
          text-align: center;
          box-sizing: border-box;
        }
      }

      .operation {
        margin-left: 20px;

        .but {
          $size: 20px;

          width: $size;
          height: $size;
          font-weight: bold;
          border: none;
          border-radius: 50%;
          color: #fff;
          background: #414059;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
